package cn.village.controller;

import cn.village.entity.VaUser;
import cn.village.service.VaUserService;
import cn.village.utils.PageSupport;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * (VaUser)表控制层
 *
 * @author makejava
 * @since 2021-02-02 10:50:42
 */
@Controller
public class VaUserController {
    /**
     * 服务对象
     */
    @Resource
    private VaUserService vaUserService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public VaUser selectOne(Integer id) {
        return this.vaUserService.queryById(id);
    }

    @RequestMapping("/village")
    public String login(){
        return "login";
    }

    @RequestMapping("/login")
    public String dologin(String userCode, String password, HttpSession session){
        VaUser vu=vaUserService.findByName(userCode);
        if(vu!=null){
            if(password.equals(vu.getPassword())){
                session.setAttribute("userName",vu.getUsername());
                return "index";
            }else {
                String err="账号密码错误，请重新登录";
                session.setAttribute("err",err);
                System.out.println(err);
                return "login";
            }
        }else {
            String err = "账号密码错误，请重新登录";
            session.setAttribute("err", err);
            System.out.println(err);
            return "login";
        }
    }

    @RequestMapping("/admin_list")
    public String goAdminList(Integer pageIndex,HttpSession session,Model model){
        PageSupport p=new PageSupport();
        p.setPageSize(5);
        int totalCount=vaUserService.findCount();
        p.setTotalCount(totalCount);
        if(pageIndex==null){
            pageIndex=1;
        }
        p.setCurrentPageNo(pageIndex);
        Integer totalPageCount=p.getTotalPageCount();
        List<VaUser> user = vaUserService.findeAll(pageIndex);
        session.setAttribute("user",user);
        model.addAttribute("totalCount",totalCount);
        model.addAttribute("currentPageNo",p.getCurrentPageNo());
        model.addAttribute("totalPageNo",totalPageCount);
        return "admin-list";
    }

    @RequestMapping("/admin_updata")
    @ResponseBody
    public VaUser updata(Integer id){
        return vaUserService.queryById(id);
    }
}